package com.xdap.keymen.service.dayang;

import com.alibaba.excel.util.StringUtils;
import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.entity.dayang.*;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
@RequiredArgsConstructor
public class DaYangStoreService extends BaseService{

    @Autowired
    OKHttpUtils okHttpUtils;

    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    DaYangShopMapService dayangShopMapService;

    @Autowired
    DaYangOrderPorductService dayangOrderPorductService;

    /***
     * 获取新零售系统库存相关订单
     * @return
     */
    public ResponseVo getStroeOrder(String startHour,String endHour) {
        int s=5;
        if (StringUtils.isNotBlank(startHour)) {
            s=Integer.parseInt(startHour);
        }
        int e=0;
        if (StringUtils.isNotBlank(endHour)) {
            e = Integer.parseInt(endHour);
        }
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        Map<String, String> params=new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        params.put("startDate", LocalDateTime.now().minusHours(s).format(formatter));
        params.put("endDate",LocalDateTime.now().minusHours(e).format(formatter));
        //params.put("orderno","202504999000267");
        log.info("getStroeOrder params:{}",params);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer "+getToken());
        Gson gson = new GsonBuilder().serializeNulls().create();
        String response = okHttpUtils.doGet(getBaseUrl().concat("/api/receipts"), params,headers);
        DayangResponse<DaYangStoreOrderEntity> dyResponse = gson.fromJson(response, new TypeToken<DayangResponse<DaYangStoreOrderEntity>>(){}.getType());
        List<DaYangStoreOrderEntity> list = new ArrayList<>();
        for (DaYangStoreOrderEntity daYangStoreOrderEntity :dyResponse.getData()) {
            DaYangStoreOrderEntity entity = getStoreOrder(daYangStoreOrderEntity.getOrderno(), daYangStoreOrderEntity.getProductid(), daYangStoreOrderEntity.getColor(), daYangStoreOrderEntity.getPsize(),daYangStoreOrderEntity.getOrderType());
            //不存在则新增
            if (entity == null) {
                DaYangShopMapEntity dayangShopMapEntity = new DaYangShopMapEntity();
                dayangShopMapEntity.setShopDayang(daYangStoreOrderEntity.getRepertory());
                DaYangShopMapEntity shop=dayangShopMapService.getShopMap(dayangShopMapEntity);
                if(shop==null){
                    log.info("getStroeOrder 店面不存在：{}",daYangStoreOrderEntity.getRepertory());
                    continue;
                }
                daYangStoreOrderEntity.setId(String.valueOf(snowflakeIdWorker.nextId()));
                daYangStoreOrderEntity.setDocumentId(snowflakeIdWorker.nextId());
                daYangStoreOrderEntity.setRepertory("[\""+shop.getShopDefan()+"\"]");
                daYangStoreOrderEntity.setFlag("1");
                //负向单据转负数
                if(daYangStoreOrderEntity.getOrderType().startsWith("2")){
                    daYangStoreOrderEntity.setQuantity(daYangStoreOrderEntity.getQuantity()*-1);
                }
                list.add(daYangStoreOrderEntity);
            }
            //处理自动匹配订单
            try{
                //测试数据
//                daYangStoreOrderEntity.setOutId("XS20250709#0001");
//                daYangStoreOrderEntity.setProductid("SW247212800");
//                daYangStoreOrderEntity.setColor("-");
//                daYangStoreOrderEntity.setDocumentId("730714844625535104");

                if(StringUtils.isNotBlank(daYangStoreOrderEntity.getOut_id()) ){
                    if(daYangStoreOrderEntity.getOrderType().contains("11") || daYangStoreOrderEntity.getOrderType().contains("12")){
                        String databaseName="xdap_app_"+runtimeAppContextService.getCurrentTenantId();
                        String posno=daYangStoreOrderEntity.getPos_id();
                        DaYangOrderTitleEntity daYangOrderTitleEntity= runtimeDatasourceService.buildTenantMpaasQuery(databaseName)
                                .eq("posno", posno)
                                .doQueryFirst(DaYangOrderTitleEntity.class);
                        if(daYangOrderTitleEntity!=null){
                            DaYangOrderProductEntity resPorduct = new DaYangOrderProductEntity();
                            resPorduct.setStyleNo(daYangStoreOrderEntity.getProductid());
                            resPorduct.setColor(daYangStoreOrderEntity.getColor());
                            resPorduct.setTabDocId(daYangOrderTitleEntity.getDocumentId());
                            DaYangOrderProductEntity rps = dayangOrderPorductService.getOrderDetail(resPorduct);
                            rps.setDanjuhaoDz(daYangStoreOrderEntity.getOut_id());
                            if(rps!=null){
                                dayangOrderPorductService.updOrderProduct(rps);
                            }
                        }

                    }

                }
            }catch (Exception exception){
                log.info("getStroeOrder 自动匹配订单异常,单号：{}",daYangStoreOrderEntity.getOrderno());
            }
        }
        if(list.size()>0){
            runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId).doBatchInsert(list);
        }
        return ResponseVo.ok();
    }

    /**
     * 检查库存记录是否存在
     * @param orderno
     * @param productid
     * @param color
     * @param size
     * @return
     */
    private DaYangStoreOrderEntity getStoreOrder(String orderno, String productid, String color, String size,String orderType) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("orderno", orderno);
        query.eq("productid", productid);
        query.eq("color", color);
        query.eq("product_size", size);
        query.eq("flag", "1");
        query.eq("order_type", orderType);
        return query.doQueryFirst(DaYangStoreOrderEntity.class);
    }
}
